package com.lcc.generate.jsp;

import com.lcc.generate.Config;
import com.lcc.generate.StringBuilder2;
import com.lcc.generate.TableConfig;
import com.lcc.generate.util.FileUtils;
import com.lcc.generate.util.JDBCUtil;
import com.lcc.generate.util.MyField;

import java.io.File;
import java.util.List;

public class Jsp2Util {

    private static String jspPath;
    private static String apiUrl;		// jsp请求路径
    private static String jspUrl;		// jsp页面路径
    private static String idName;		// 主键 驼峰
    private static List<MyField> fields;
    private static Config generateConfig;

    public static void createJsp(List<MyField> fieldArr, TableConfig config, Config gConfig) {
        generateConfig = gConfig;
        jspPath = gConfig.jspPath;
        //初始化
        String tableName = config.getTableName(generateConfig.ifNoPrefix);
        apiUrl = tableName.replace("_", "/");
        jspUrl = JDBCUtil.toHump(tableName);
        jspPath = jspPath + "/" + jspUrl;
        fields = fieldArr;
        idName = "";
        for (MyField field : fields) {
            if(field.column.equals(config.primaryKey)){
                idName = field.name;
            }
        }

        File jspRoot = new File(jspPath);
        if(!jspRoot.exists()){
            jspRoot.mkdirs();
        }
        File file = new File(jspRoot, "index.jsp");
        if(!file.exists() || generateConfig.coverVueIndex){
            StringBuilder2 indexSB = FileUtils.getTempString("temp/jsp2/index.jsp");
            indexSB.replace("${queryCondition}", getQueryCondition())
                    .replace("${apiUrl}", apiUrl)
                    .replace("${idName}", idName);
            FileUtils.write(file, indexSB.toString());
            System.out.println("生成：" + jspPath + "/index.jsp");
        }

        file = new File(jspRoot, "index.js");
        if(!file.exists() || generateConfig.coverVueIndex){
            StringBuilder2 indexSB = FileUtils.getTempString("temp/jsp2/index.js");
            indexSB.replace("${zbTableColumns}", zbTableColumns())
                    .replace("${apiUrl}", apiUrl)
                    .replace("${idName}", idName);
            FileUtils.write(file, indexSB.toString());
            System.out.println("生成：" + jspPath + "/index.js");
        }

        file = new File(jspRoot, "add.jsp");
        if(!file.exists() || generateConfig.coverVueAdd){
            StringBuilder2 addSB = FileUtils.getTempString("temp/jsp/add.jsp");
            addSB.replace("${formItems}", getFormItems(false))
                    .replace("${apiUrl}", apiUrl);
            FileUtils.write(file, addSB.toString());
            System.out.println("生成：" + jspPath + "/add.jsp");
        }

        file = new File(jspRoot, "edit.jsp");
        if(!file.exists() || generateConfig.coverVueUpdate){
            StringBuilder2 updateSB = FileUtils.getTempString("temp/jsp/edit.jsp");
            updateSB.replace("${formItems}", getFormItems(true))
                    .replace("${apiUrl}", apiUrl);
            FileUtils.write(file, updateSB.toString());
            System.out.println("生成：" + jspPath + "/edit.jsp");
        }
    }

    private static String getFormItems(boolean ifUpdate) {
        StringBuilder formItems = new StringBuilder();
        for (MyField field : fields) {
            if(field.isSkip) continue;
            if(field.name.equals(idName)){
                if(!ifUpdate) {
                    continue;
                }else {
                    formItems.insert(0, String.format("\t\t\t" +
                            "<input type=\"hidden\" name=\"%s\" value=\"${entity.%s}\"/>\n", field.name, field.name));
                    continue;
                }
            }
            if(!ifUpdate && field.name.equals(idName)) continue;
            String must = field.required ? " class=\"must\"" : "             ";
            String required = field.required ? " required" : "";
            String required2 = field.required ? " required=\"true\"" : "";
            String spaceStr = "";
            int i = 24 - must.length() - field.label.length()*2;
            for (int j = 0; j < i; j++) {
                spaceStr += " ";
            }
            if(field.isTime) {

            }else if(field.dictCode != null){
                formItems.append(String.format("\t\t\t" +
                                "<dl><dt%s>%s:</dt><dd>%s\t<zbiti:dictSelect code=\"%s\" name=\"%s\" value=\"%s\"%s></zbiti:dictSelect></dd></dl>\n",
                        must, field.label, spaceStr, field.dictCode, field.name, ifUpdate ? ("${entity." + field.name + "}") : "", required2));
            }else {

                formItems.append(String.format("\t\t\t" +
                                "<dl><dt%s>%s:</dt><dd>%s\t<input type=\"text\" name=\"%s\" value=\"%s\"%s/></dd></dl>\n",
                        must, field.label, spaceStr, field.name, ifUpdate ? ("${entity." + field.name + "}") : "", required));
            }
        }
        return formItems.toString();
    }

    private static String getQueryCondition() {
        StringBuilder queryCondition = new StringBuilder();
        for (MyField field : fields) {
            if(field.isSkip) continue;
            if(field.isTime) {
                if(!"time".equals(field.searchType)) continue;
                queryCondition.append(String.format(
                        """
                                            <div class="query-item" style="width: 380px">
                                                <div class="query-label">%s：</div>
                                                <div class="query-content">
                                                    <input name="%sStart" type="text" style="width: 100px;" readOnly class="date"/>~
                                                    <input name="%sStartEnd" type="text" style="width: 100px;" readOnly class="date"/>
                                                </div>
                                            </div>
                        """, field.label, field.name, field.name));
            }else if(field.dictCode != null){
                queryCondition.append(String.format(
                        """
                                            <div class="query-item">
                                                <div class="query-label">%s：</div>
                                                <div class="query-content">
                                                    <zbiti:dictSelect code="%s" name="%s"></zbiti:dictSelect>
                                                </div>
                                            </div>
                        """, field.label, field.dictCode, field.name));
            }else if(field.searchType != null && field.searchType.contains("like")){
                queryCondition.append(String.format(
                        """
                                            <div class="query-item">
                                                <div class="query-label">%s：</div>
                                                <div class="query-content">
                                                    <input type="text" name="%sLike"/>
                                                </div>
                                            </div>
                        """, field.label, field.name));
            }else {
                queryCondition.append(String.format(
                        """
                                            <div class="query-item">
                                                <div class="query-label">%s：</div>
                                                <div class="query-content">
                                                    <input type="text" name="%s"/>
                                                </div>
                                            </div>
                        """, field.label, field.name));
            }
        }
        return queryCondition.toString();
    }

    private static String zbTableColumns() {
        StringBuilder fieldValues = new StringBuilder();
        for (MyField field : fields) {
            if(field.isSkip) continue;
            if(field.dictCode != null) {fieldValues.append(String.format("\t\t\t" +
                    "<zb-table-column prop=\"%s\" label=\"%s\" code=\"%s\"></zb-table-column>\n", field.name, field.label, field.dictCode));
            }else if(field.isTime){fieldValues.append(String.format("\t\t\t" +
                    "<zb-table-column prop=\"%s\" label=\"%s\" fmt=\"TF\" width=\"160px\"></zb-table-column>\n", field.name, field.label));
            }else{fieldValues.append(String.format("\t\t\t" +
                    "<zb-table-column prop=\"%s\" label=\"%s\"></zb-table-column>\n", field.name, field.label));
            }
        }
        return fieldValues.toString();
    }

}
